import { NextRequest, NextResponse } from 'next/server'

interface ProtectionSettings {
  stallProtection: string
  stallHoldTime: string
  stallRestartTime: string
  stallRestartCount: string
  overvoltageProtection: string
  overvoltageValue: string
  overvoltageRecoveryValue: string
  undervoltageProtection: string
  undervoltageValue: string
  undervoltageRecoveryValue: string
  temperatureProtection: string
  protectionTemp: string
  recoveryTemp: string
  overcurrentProtection: string
  overcurrentValue: string
  currentLimitProtection: string
  currentLimitValue: string
  blockageProtection: string
  blockageDiameter: string
  blockageHoldTime: string
  phaseProtection: string
}

// 模拟保护设置数据存储
const protectionSettingsStore: Record<string, ProtectionSettings> = {}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const projectId = (await params).id
    
    // 返回项目的保护设置
    const settings = protectionSettingsStore[projectId] || {
      stallProtection: "无",
      stallHoldTime: "",
      stallRestartTime: "",
      stallRestartCount: "",
      overvoltageProtection: "无",
      overvoltageValue: "",
      overvoltageRecoveryValue: "",
      undervoltageProtection: "无",
      undervoltageValue: "",
      undervoltageRecoveryValue: "",
      temperatureProtection: "无",
      protectionTemp: "",
      recoveryTemp: "",
      overcurrentProtection: "无",
      overcurrentValue: "",
      currentLimitProtection: "无",
      currentLimitValue: "",
      blockageProtection: "无",
      blockageDiameter: "",
      blockageHoldTime: "",
      phaseProtection: "无"
    }

    return NextResponse.json(settings)
  } catch (error) {
    console.error('获取保护设置失败:', error)
    return NextResponse.json(
      { error: '获取保护设置失败' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const projectId = (await params).id
    const body = await request.json()
    
    // 验证必要字段
    const requiredFields = [
      'stallProtection', 'overvoltageProtection', 'undervoltageProtection',
      'temperatureProtection', 'overcurrentProtection', 'currentLimitProtection',
      'blockageProtection', 'phaseProtection'
    ]
    
    for (const field of requiredFields) {
      if (body[field] === undefined) {
        return NextResponse.json(
          { error: `缺少必要字段: ${field}` },
          { status: 400 }
        )
      }
    }
    
    // 验证保护参数的逻辑一致性
    if (body.stallProtection !== "无") {
      if (!body.stallHoldTime) {
        return NextResponse.json(
          { error: '堵转保护启用时，保持时间不能为空' },
          { status: 400 }
        )
      }
      
      if (body.stallProtection === "有，自恢复") {
        if (!body.stallRestartTime || !body.stallRestartCount) {
          return NextResponse.json(
            { error: '堵转自恢复模式需要填写重启时间和重启次数' },
            { status: 400 }
          )
        }
      }
    }
    
    if (body.overvoltageProtection !== "无") {
      if (!body.overvoltageValue) {
        return NextResponse.json(
          { error: '过压保护启用时，保护值不能为空' },
          { status: 400 }
        )
      }
      
      if (body.overvoltageProtection === "有，自恢复" && !body.overvoltageRecoveryValue) {
        return NextResponse.json(
          { error: '过压自恢复模式需要填写恢复值' },
          { status: 400 }
        )
      }
    }
    
    if (body.undervoltageProtection !== "无") {
      if (!body.undervoltageValue) {
        return NextResponse.json(
          { error: '欠压保护启用时，保护值不能为空' },
          { status: 400 }
        )
      }
      
      if (body.undervoltageProtection === "有，自恢复" && !body.undervoltageRecoveryValue) {
        return NextResponse.json(
          { error: '欠压自恢复模式需要填写恢复值' },
          { status: 400 }
        )
      }
    }
    
    if (body.temperatureProtection !== "无") {
      if (!body.protectionTemp) {
        return NextResponse.json(
          { error: '温度保护启用时，保护温度不能为空' },
          { status: 400 }
        )
      }
      
      if (body.temperatureProtection === "有，自恢复" && !body.recoveryTemp) {
        return NextResponse.json(
          { error: '温度自恢复模式需要填写恢复温度' },
          { status: 400 }
        )
      }
    }
    
    if (body.overcurrentProtection !== "无" && !body.overcurrentValue) {
      return NextResponse.json(
        { error: '过流保护启用时，保护值不能为空' },
        { status: 400 }
      )
    }
    
    if (body.currentLimitProtection === "有" && !body.currentLimitValue) {
      return NextResponse.json(
        { error: '限流保护启用时，限流值不能为空' },
        { status: 400 }
      )
    }
    
    if (body.blockageProtection !== "无") {
      if (!body.blockageDiameter || !body.blockageHoldTime) {
        return NextResponse.json(
          { error: '堵孔保护启用时，孔径和保持时间不能为空' },
          { status: 400 }
        )
      }
    }
    
    // 保存保护设置
    protectionSettingsStore[projectId] = body
    
    console.log('保护设置已更新:', { projectId, ...body })
    
    return NextResponse.json({ 
      message: '保护设置更新成功',
      settings: body
    })
  } catch (error) {
    console.error('更新保护设置失败:', error)
    return NextResponse.json(
      { error: '更新保护设置失败' },
      { status: 500 }
    )
  }
}